<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <style>
      div {
        border: solid;
      }

      #box1 {
        width: 600px;
        height: 600px;
        margin: 100px 0 0 100px;
        position: relative;
      }
      #box2 {
        width: 100px;
        height: 100px;
        background: yellow;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="box1">
      <div id="box2"></div>
    </div>

    <script>
      const box1 = document.getElementById("box1");
      const box2 = document.getElementById("box2");

      // 1、当鼠标在box2 上按下的时候触发移动跟随
      box2.onmousedown = function (e2) {
        // 鼠标相对于box2坐标
        const box2Pos = box2.getBoundingClientRect();
        const x2 = e2.clientX - box2Pos.left;
        const y2 = e2.clientY - box2Pos.top;

        // box2 鼠标跟随
        box1.onmousemove = function (e) {
          // 获取鼠标相对于目标元素的坐标
          const x = e.clientX - box1.offsetLeft;
          const y = e.clientY - box1.offsetTop;
          const bx = x - x2;
          const by = y - y2;

          // 计算边界，移动box2
          if (bx < 0) {
            // 左边界 （如果越过边界值，直接等于边界值）
            box2.style.left = "0px";
          } else if (bx > box1.offsetWidth - box2.offsetWidth) {
            // 右边界（如果越过边界值，直接等于边界值）
            box2.style.left = box1.offsetWidth - box2.offsetWidth + "px";
          } else {
            box2.style.left = bx + "px";
          }

          if (by < 0) {
            box2.style.top = "0px";
          } else if (by > box1.offsetHeight - box2.offsetHeight) {
            box2.style.top = box1.offsetHeight - box2.offsetHeight + "px";
          } else {
            box2.style.top = by + "px";
          }
        };
      };
      // 2、抬起的时候取消移动跟随
      box2.onmouseup = function () {
        box1.onmousemove = null;
      };
      // 当鼠标从box2上移开的时候取消跟随
      box2.onmouseout = function () {
        box1.onmousemove = null;
      };
    </script>
  </body>
</html>
